#pragma once
#include <iostream>
#include <cstring>
#include <pthread.h>
#include <unistd.h>
#include <netinet/in.h>
#include <functional>
#include <arpa/inet.h>
#include <sys/types.h>          
#include <sys/socket.h>
#include <sys/wait.h>
#include "nocopy.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"
#include"log.hpp"
#include"threadpool.hpp"
//static const int gsockfd = -1;
static const int gblcklog = 5;//默认监听的个数
using task_t = function<void(void)>;
using service_t = function<void(SockSPtr,InetAddr&)>;
class Server
{

public:
	Server(uint16_t localport,service_t service)
		:_localport(localport),_listensock(std::make_shared<TcpSocket>()),_isruning(false),_service(service)
	{
		_listensock->BuildListenSocket(_localport);
	};
	struct ServerData//这个结构体是为了方便线程通过void*拿到所有需要的参数
	{
	ServerData(SockSPtr sock,Server* self,InetAddr client)
		:_sock(sock),_self(self),_client(client)
	{
	};
	SockSPtr _sock;
	Server* _self;
	InetAddr _client;
	};
	void Start()
	{
		_isruning = true;
		while(_isruning)
		{
			InetAddr Client;
			SockSPtr sock =_listensock->Accepter(&Client);
			if(sock==nullptr)
				continue;
			//实现业务
			pthread_t tid;
			ServerData* sd =new ServerData(sock,this,Client);
			pthread_create(&tid,nullptr,Execute,sd);

		};
	}
	static void* Execute(void* args)//线程传参函数
	{
		pthread_detach(pthread_self());
		ServerData* sd = static_cast<ServerData*>(args);
		sd->_self->_service(sd->_sock,sd->_client);
		delete sd;
		return nullptr;
	};

private:
	uint16_t _localport;
	SockSPtr _listensock;
	bool _isruning;//这个参数在本程序作用不大，但是是服务器不可缺少的
	service_t _service;
};
